package com.terenac;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginForm extends Activity{

	public String errorMsg;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		Button btn_demo = (Button) findViewById(R.id.buttonLogin);
	    btn_demo.setOnClickListener(new OnClickListener()
	    {
			public void onClick(View v) 
			{

	 	 		User.setUsername(getUserName());
	 	 		User.setPassword(getPassword());
	 	 		boolean success = checkUserNameAndPass(User.getUsername(), SecurityManager.Encrypt(User.getPassword()));

	 	 		if (success)
	 	 		{
	 	 			Intent i = new Intent();
                    i.setClass(LoginForm.this, MainMenuForm.class);
                    startActivity(i);
	 	 			//startActivity(new Intent("com.prviprojekt.MAINMENUSCREEN"));
	 	 		}
	 	 		else
	 	 		{
	 	 			
	 	 			TextView errorLabel = (TextView) findViewById(R.id.textError);
	 	 			errorLabel.setTextColor(Color.RED);
					errorLabel.setText(errorMsg);
	 	 			EditText user = (EditText) findViewById(R.id.editUsername); 
	 	 			user.setText(User.getUsername());
		 	 		EditText pass = (EditText) findViewById(R.id.editPassword); 
		 	 		pass.setText("");	 	 			
	 	 		}
			}
	    });
	}

	private String getUserName()
	{
		EditText user = (EditText) findViewById(R.id.editUsername); 
	 	 	return user.getText().toString();
	}
	
	private String getPassword()
	{
	 		EditText pass = (EditText) findViewById(R.id.editPassword); 
	 	 	return pass.getText().toString();
	}
	
	private boolean checkUserNameAndPass(String userName, String pass)
	{
		//za testiranje
		//if (true) return true;
		String id = null;
		try{
			id = PostService.sendLoginRequest(userName, pass);
		}catch (Exception e) {
			// TODO: handle exception
			this.errorMsg = e.getMessage();
			return false;
		}
		if (id.equals("0")){
			this.errorMsg = "Wrong username or password.";
			return false;
		}
		else{
			User.setSessionId(id);
			return true;
		}
	}
}
